use anyhow::{Result, Context};

use crate::hotcure_parse_opts;
use hotcure_parse_opts::{Opts, Action};
use hotcure_parse_opts::{Patch, Unpatch, Info};

fn hotcure_process_patch (patch: &Patch) -> Result<()> {
    println!("patch args: {:?}", patch);
    Ok(())
}

fn hotcure_process_unpatch (unpatch: Unpatch) -> Result<()> {
    println!("unpatch args: {:?}", unpatch);
    Ok(())
}

fn hotcure_process_info (info: Info) -> Result<()> {
    println!("info args: {:?}", info);
    Ok(())
}

pub fn run (opts: Opts) -> Result<()> {
    match opts.action {
        Action::Patch(patch) => {
            info!("Applying patch '{}' to PID '{}'",
                  patch.patch_file.to_str().unwrap(), patch.pid);

            if let Err(e) = hotcure_process_patch(&patch) {
                error!("Failed to apply patch '{}' to PID '{}'",
                       patch.patch_file.to_str().unwrap(), patch.pid);
                return Err(e).with_context(||
                    format!("Failed to apply patch '{}' to PID '{}'",
                            patch.patch_file.to_str().unwrap(), patch.pid));
            }

            info!("Patch '{}' has been successfully applied to PID '{}'",
                  patch.patch_file.to_str().unwrap(), patch.pid);
        },

        Action::Unpatch(unpatch) => hotcure_process_unpatch(unpatch)?,
        Action::Info(info) => hotcure_process_info(info)?,
    }
    Ok(())
}